package work.linruchang.util.bean.wrapper.db;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.StrUtil;
import lombok.Data;
import lombok.experimental.Accessors;
import work.linruchang.util.EnhanceStrUtil;

import javax.persistence.Table;
import java.io.Serializable;

/**
 * 表信息
 *
 * @author LinRuChang
 * @version 1.0
 * @date 2022/01/17
 * @since 1.8
 **/
@Accessors(chain = true)
@Data
public class TableInfo implements Serializable {

    /**
     * 表对应的Bean
     */
    Class dbBeanClazz;

    /**
     * 表名
     */
    String tableName;

    /**
     * 表别名
     * 格式：表名中每个单词首字母小写+UUID的前五位字符
     */
    String tableAlias;

    /**
     * 是否是主表
     */
    Boolean masterTableFlag = false;

    public TableInfo(Class dbBeanClazz, boolean masterTableFlag) {
        this(dbBeanClazz);
        this.masterTableFlag = masterTableFlag;
    }

    public TableInfo(Class dbBeanClazz) {
        this.dbBeanClazz = dbBeanClazz;
        this.tableName = getTableNameByAnnotation();
        Assert.notBlank(tableName, "表名缺失，查看Bean是否缺失javax.persistence.Table注解");
        String tableAlias = StrUtil.join(StrUtil.UNDERLINE, EnhanceStrUtil.firstCharEachWord(getTableName()), StrUtil.sub(UUID.fastUUID().toString(true), 0, 5));
        this.setTableAlias(tableAlias);
    }


    private void setDbBeanClazz(Class dbBeanClazz) {
        this.dbBeanClazz = dbBeanClazz;
    }

    private void setTableName(String tableName) {
        this.tableName = tableName;
    }

    private void setTableAlias(String tableAlias) {
        this.tableAlias = tableAlias;
    }


    /**
     * 获取表名
     *
     * @return
     */
    protected String getTableNameByAnnotation() {
        String tableName = null;
        if (dbBeanClazz != null) {
            Table tableAnnotation = (Table) dbBeanClazz.getAnnotation(Table.class);
            return tableAnnotation != null ? tableAnnotation.name() : null;
        }
        return tableName;
    }
}
